const errcode = require('../utils/errcode')
const models = require('../models')
const service = require('../service')
const config = require('../config')

module.exports = async (ctx, next) => {
  ctx.config = config
  ctx.models = models
  ctx.service = service

  ctx.getLoginUser = async function () {
    let loginId = ctx.session.loginId
    const token = ctx.session.token || ctx.request.body.token || ctx.query.token

    if (!loginId && token) {
      const tokenInfo = await models.token.getValidToken(token)

      if (tokenInfo) {
        loginId = tokenInfo.userId
      }
    }

    if (!loginId) return null

    const user = await ctx.models.user.getUserInfo(loginId)

    return user
  }

  ctx.success = (data) => {
    ctx.body = { ...errcode.SUCCESS, data: data }
  }

  ctx.error = (msg, data) => {
    if (typeof msg === 'object') {
      ctx.body = { ...msg, data }
    } else {
      ctx.body = { ...errcode.UNKNOW_ERROR, msg, data }
    }
  }

  await next()
}
